package com.demo.java.delayqueue;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * jdk 延迟队列测试
 */
@Slf4j
public class JDKDelayQueueTest {

    @Data
    static class Order implements Delayed {
        private long time;// 延迟到什么时候
        private long value;
        public Order(long delayTime, long value) {
            this.time = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(delayTime);
            this.value = value;
        }
        @Override
        public long getDelay(TimeUnit unit) {
            return time - System.currentTimeMillis();
        }

        @Override
        public int compareTo(Delayed o) {
            Order order = (Order) o;
            return this.time - order.getTime() <= 0 ? -1 : 1;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Order order1 = new Order(5, 1);
        Order order2 = new Order(10, 2);
        Order order3 = new Order(15, 3);

        DelayQueue<Order> delayQueue = new DelayQueue<>();
        delayQueue.add(order1);
        delayQueue.add(order2);
        delayQueue.add(order3);

        log.info("delay queue start");
        while (delayQueue.size() > 0) {
            Order poll = delayQueue.poll();
            if (Objects.nonNull(poll)) {
                log.info("order" + poll.getValue());
            }
            Thread.sleep(100);
        }
        log.info("end");
    }
}
